package hibernate;

import java.io.File;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author Thorsten Ludwig
 */
public class HibernateUtil { 

    private static final SessionFactory sessionFactory;
    private static final Session session;
      
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.            
            FacesContext context = FacesContext.getCurrentInstance();
            ServletContext sc = (ServletContext) context.getExternalContext().getContext();
            System.out.println(sc.getRealPath("") + " ist der aktuelle Pfad");
            
            File f = new File(sc.getRealPath("") + "/hibernate.cfg.xml");      
            System.out.println("hibernate.cfg.xml gefunden: " + f.exists());
            System.out.println("Versuche, Configuration zu erstellen");
            Configuration c = new Configuration().configure(f);
            System.out.println("Erstelle buildSesionFactory");
            
            sessionFactory = c.buildSessionFactory();
            session = sessionFactory.getCurrentSession();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static Session getSession() {
        return sessionFactory.getCurrentSession();
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void update(Object o) {
        Session s = HibernateUtil.getSession();
        s.beginTransaction();
        s.saveOrUpdate(o);
        s.getTransaction().commit();
    }
    
    public static void delete(Object o) {
        Session s = HibernateUtil.getSession();
        s.beginTransaction();
        s.delete(o);
        s.getTransaction().commit();
    }
}
